package com.uduemc.jcms.config.upload;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import com.uduemc.jcms.config.basic.JcmsBasicConfig;
import com.uduemc.jcms.config.upload.conf.JCMSUploadConfigAudio;
import com.uduemc.jcms.config.upload.conf.JCMSUploadConfigFile;
import com.uduemc.jcms.config.upload.conf.JCMSUploadConfigFlash;
import com.uduemc.jcms.config.upload.conf.JCMSUploadConfigImage;
import com.uduemc.jcms.config.upload.conf.JCMSUploadConfigVideo;

import cn.hutool.core.util.NumberUtil;
import lombok.Data;

@Data
@Component(value = "jcmsUploadConfig")
@ConfigurationProperties(prefix = "jcms.upload")
public class JcmsUploadConfig {
	String entrance = "repertory";
	JCMSUploadConfigImage image = new JCMSUploadConfigImage();
	JCMSUploadConfigFile file = new JCMSUploadConfigFile();
	JCMSUploadConfigFlash flash = new JCMSUploadConfigFlash();
	JCMSUploadConfigVideo video = new JCMSUploadConfigVideo();
	JCMSUploadConfigAudio audio = new JCMSUploadConfigAudio();

	@Autowired
	JcmsBasicConfig jcmsBasicConfig;

	public String filepath() {
		return jcmsBasicConfig.getPath() + File.separator + this.getEntrance();
	}

	public static long makeValidSize(String value, long defaultSize) {
		String numberOnly = value.replaceAll("[^0-9]$", "");
		if (NumberUtil.isNumber(numberOnly)) {
			Long sizeOf = Long.valueOf(numberOnly);
			if (sizeOf == null || sizeOf <= 0) {
				throw new RuntimeException("无法解析 value：" + value);
			}

			String unit = value.replaceAll(numberOnly, "").toUpperCase();
			if (unit.equals("G") || unit.equals("GB")) {
				return sizeOf * 1024 * 1024 * 1024L;
			} else if (unit.equals("M") || unit.equals("MB")) {
				return sizeOf * 1024 * 1024L;
			} else if (unit.equals("K") || unit.equals("KB")) {
				return sizeOf * 1024L;
			} else if (unit.equals("B")) {
				return sizeOf * 1L;
			} else {
				return defaultSize;
			}
		}
		throw new RuntimeException("无法解析 value：" + value);
	}

	public List<String> allowSuffix() {
		List<String> suffix = new ArrayList<String>();
		if (this.getImage().isEnabled()) {
			suffix.addAll(Arrays.asList(this.getImage().getExt()));
		}
		if (this.getFile().isEnabled()) {
			suffix.addAll(Arrays.asList(this.getFile().getExt()));
		}
		if (this.getFlash().isEnabled()) {
			suffix.addAll(Arrays.asList(this.getFlash().getExt()));
		}
		if (this.getVideo().isEnabled()) {
			suffix.addAll(Arrays.asList(this.getVideo().getExt()));
		}
		if (this.getAudio().isEnabled()) {
			suffix.addAll(Arrays.asList(this.getAudio().getExt()));
		}
		return suffix;
	}
}
